package com.hyg.lib_music.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.BassBoost;
import android.media.audiofx.Equalizer;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;

import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.DataModel.Music.PlayingMusic;
import com.hyg.lib_music.R;
import com.hyg.lib_music.util.MusicChangeEvent;
import com.kingsoft.media.httpcache.KSYProxyService;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MusicService extends Service {

    //播放模式
    public static final int TYPE_ORDER = 0;  //顺序播放
    public static final int TYPE_SINGLE = 4313; //单曲循环
    public static final int TYPE_RANDOM = 4414; //随机播放

    private MediaPlayer player;
    private List<Music> playingMusicList;
    private List<OnStateChangeListenr> listenrList;
    private MusicServiceBinder binder;
    private AudioManager audioManager;
    private Music currentMusic; // 当前就绪的音乐
    private  boolean autoPlayAfterFocus;    // 获取焦点之后是否自动播放
    private boolean isNeedReload;     // 播放时是否需要重新加载
    private SharedPreferences spf;
    private PendingIntent pendingIntent;
    private long stopMusicTimeMillis;
    private KSYProxyService proxy;
    // 定义系统的重低音控制器
    private BassBoost mBass;
    // 定义系统的均衡器
    private Equalizer mEqualizer;
    public int Music_image= R.mipmap.yangsheng_music_icon;
    @Override
    public void onCreate() {
        super.onCreate();
        initPlayList();     //初始化播放列表
        listenrList = new ArrayList<>();    //初始化监听器列表
        player = new MediaPlayer();   //初始化播放器
        player.setOnCompletionListener(onCompletionListener);   //设置播放完成的监听器
        player.setOnErrorListener(onErrorListener);   //设置播放错误的监听器
        player.setOnPreparedListener(onPreparedListener);
        binder = new MusicServiceBinder();
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); //获得音频管理服务

        proxy = BaseApplication.getProxy(BaseApplication.getInstance());
        proxy.startServer();

        mBass = new BassBoost(0, player.getAudioSessionId());
        // 设置启用重低音效果
        mBass.setEnabled(true);

        // 以MediaPlayer的AudioSessionId创建Equalizer
        // 相当于设置Equalizer负责控制该MediaPlayer
        mEqualizer = new Equalizer(0, player.getAudioSessionId());
        // 启用均衡控制效果
        mEqualizer.setEnabled(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player.isPlaying()) {
            player.stop();
        }
        player.release();

        playingMusicList.clear();
        listenrList.clear();
        handler.removeMessages(66);
        try {
            unregisterReceiver(stopMusicReceiver);
        } catch (IllegalArgumentException e) {

        }
        audioManager.abandonAudioFocus(audioFocusListener); //注销音频管理服务
    }

    //对外监听器接口
    public interface OnStateChangeListenr {
        void onPlayProgressChange(long played, long duration);  //播放进度变化
        void onPlay(Music item);    //播放状态变化
        void onPause();   //播放状态变化
    }

    //定义binder与活动通信
    public class MusicServiceBinder extends Binder {

        // 添加一首歌曲
        public void addPlayList(Music item) {
            addPlayListInner(item);
        }

        // 添加多首歌曲
        public void addPlayList(List<Music> items, Music current) {
            addPlayListInner(items, current);
        }

        // 移除一首歌曲
        public void removeMusicById(int musicId) {
            removeMusicByIdInner(musicId);
        }

        // 移除一首歌曲
        public void removeMusic(int i) {
            removeMusicInner(i);
        }

        public void playOrPause(){
            if (player.isPlaying()){
                pauseInner();
            }
            else {
                playInner();
            }
        }
        /**
         * 初始化均衡控制器
         */
        public void UpdateSetEqualizer(int progress,boolean high)
        {
            // 获取均衡控制器支持最小值和最大值
            final short minEQLevel = mEqualizer.getBandLevelRange()[0];//第一个下标为最低的限度范围
            short maxEQLevel = mEqualizer.getBandLevelRange()[1];  // 第二个下标为最高的限度范围
            // 获取均衡控制器支持的所有频率
            short brands = mEqualizer.getNumberOfBands();
            int MaxLevel = maxEQLevel - minEQLevel;
            for (short i = 0; i < brands; i++)
            {
                int frequancy = mEqualizer.getCenterFreq(i) / 1000;
                if(high){
                    if( frequancy > 500 ){
                        mEqualizer.setBandLevel(i,(short) ((progress * 0.001 * MaxLevel) + minEQLevel));
                    }else{
                        continue;
                    }
                }else{
                    if( frequancy <= 500 ){
                        //                    final short brand = i;
                        mEqualizer.setBandLevel(i,(short) ((progress * 0.001 * MaxLevel) + minEQLevel));
                    }else{
                        continue;
                    }
                }
            }
        }

        // 下一首
        public void playNext() {
            playNextInner();
        }

        // 上一首
        public void playPre() {
            playPreInner();
        }

        // 获取当前播放模式
        public int getPlayMode(){
            return getPlayModeInner();
        }

        // 设置播放模式
        public void setPlayMode(int mode){
            setPlayModeInner(mode);
        }

        // 设置播放器进度
        public void seekTo(int pos) {
            seekToInner(pos);
        }

        // 获取当前就绪的音乐
        public Music getCurrentMusic() {
            return getCurrentMusicInner();
        }

        // 获取播放器播放状态
        public boolean isPlaying() {
            return isPlayingInner();
        }

        // 获取播放列表
        public List<Music> getPlayingList() {
            return getPlayingListInner();
        }

        // 注册监听器
        public void registerOnStateChangeListener(OnStateChangeListenr l) {
            listenrList.add(l);
        }

        // 注销监听器
        public void unregisterOnStateChangeListener(OnStateChangeListenr l) {
            listenrList.remove(l);
        }
        // 定时关闭
        public void stopMusicAlarm(int second) {
            startMusicAlarmInner(second);
        }

        // 取消定时
        public void cancelMusicAlarm() {
            cancelMusicAlarmInner();
        }

        // 剩余时间
        public long getMusicAlarmLimit() {
            return getMusicAlarmLimitInner();
        }

        // 设置重低音
        public void setStrength(int progress) {
            setStrengthInner(progress);
        }

        // 当前重低音量
        public int getStrength() {
            return getStrengthInner();
        }
        // 获取图片地址
        public int getImagePath() {
            return Music_image;
        }

        // 设置图片地址
        public void setImagePath(int path) {
            Music_image=path;
        }

    }
    //添加到播放列表
    private void addPlayListInner(Music music){
        if (!playingMusicList.contains(music)) {
            playingMusicList.add( music);
//            PlayingMusic playingMusic = new PlayingMusic(music.id, music.musicName,music.musician,music.musicDuration,music.region,music.musicUrl,music.cateId,music.cateName,music.isWhite);
//            playingMusic.save();
        }
        currentMusic = music;
        isNeedReload = true;
        playInner();
    }

    private void addPlayListInner(List<Music> musicList, Music current){
        playingMusicList.clear();
        LitePal.deleteAll(PlayingMusic.class);
        playingMusicList.addAll(musicList);
//        for (Music music: musicList){
//            PlayingMusic playingMusic = new PlayingMusic(music.id, music.musicName,music.musician,music.musicDuration,music.region,music.musicUrl,music.cateId,music.cateName,music.isWhite);
//            playingMusic.save();
//        }
        currentMusic = current;//playingMusicList.get(0);
        isNeedReload = true;
        playInner();
    }

    private void removeMusicInner(int i){
//        LitePal.deleteAll(PlayingMusic.class, "musicName=?", playingMusicList.get(i).musicName);
        playingMusicList.remove(i);
    }

    private void removeMusicByIdInner(int id){

//        LitePal.deleteAll(PlayingMusic.class, "id=?", id+"");
        for (Music music : playingMusicList) {
            if (music.id == id){
                playingMusicList.remove(music);
                break;
            }
        }
    }

    private void playInner() {

//        Log.i("MusicService-------", "playInner(): " + currentMusic.musicName);
        //获取音频焦点
        audioManager.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

        //如果之前没有选定要播放的音乐，就选列表中的第一首音乐开始播放
        if (currentMusic == null && playingMusicList.size() > 0) {
            Log.i("MusicService-------", "playInner(): true" + currentMusic.musicName);
            currentMusic = playingMusicList.get(0);
            isNeedReload = true;
        }

        playMusicItem(currentMusic, isNeedReload);

    }

    private void pauseInner(){
        player.pause();

        for (OnStateChangeListenr l : listenrList) {
            l.onPause();
        }
        // 暂停后不需要重新加载
        Log.i("MusicService-------", "pauseInner()--");
        isNeedReload = false;
    }

    private void playPreInner(){
        //获取当前播放（或者被加载）音乐的上一首音乐
        //如果前面有要播放的音乐，把那首音乐设置成要播放的音乐
        if (getPlayModeInner() == TYPE_RANDOM){
            int currentIndex = playingMusicList.indexOf(currentMusic);
            //随机播放
            int i = (int) (0 + Math.random() * (playingMusicList.size()-1 ));
            if (currentIndex == i)
            {
                //如果还是这首再次随机
                i = (int) (0 + Math.random() * (playingMusicList.size()-1 ));
            }
            currentMusic = playingMusicList.get(i);
        }
        else {
            //列表循环
            int currentIndex = playingMusicList.indexOf(currentMusic);
            if (currentIndex - 1 >= 0) {
                currentMusic = playingMusicList.get(currentIndex - 1);
            }else {
                currentMusic = playingMusicList.get(playingMusicList.size() - 1);
            }
        }
        isNeedReload = true;
        Log.i("MusicService-------", "playPreInner()--");
        playInner();
    }

    private void playNextInner() {

        if (getPlayModeInner() == TYPE_RANDOM){
            int currentIndex = playingMusicList.indexOf(currentMusic);
            //随机播放
            int i = (int) (0 + Math.random() * (playingMusicList.size()-1 ));
            if (currentIndex == i)
            {
                //如果还是这首再次随机
                i = (int) (0 + Math.random() * (playingMusicList.size()-1 ));
            }
            currentMusic = playingMusicList.get(i);
        }
        else {
            //列表循环
            int currentIndex = playingMusicList.indexOf(currentMusic);
            if (currentIndex < playingMusicList.size() - 1) {
                currentMusic = playingMusicList.get(currentIndex + 1);
            } else {
                currentMusic = playingMusicList.get(0);
            }
        }
        isNeedReload = true;
        Log.i("MusicService-------", "playNextInner: " + currentMusic.musicName);
        playInner();
    }

    private void seekToInner(int pos){
        //将音乐拖动到指定的时间
        player.seekTo(pos);
    }

    private void cancelMusicAlarmInner() {
        if (pendingIntent != null){

            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
            pendingIntent.cancel();//important
            pendingIntent = null;
            stopMusicTimeMillis = 0;
        }
    }

    private void startMusicAlarmInner(int second) {
        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        stopMusicTimeMillis = SystemClock.elapsedRealtime()+second*1000;

        IntentFilter intentFilter = new IntentFilter(STOP_MUSIC_ACTION);
        registerReceiver(stopMusicReceiver, intentFilter);
        Intent intent = new Intent();
        intent.setAction(STOP_MUSIC_ACTION);
        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,stopMusicTimeMillis,pendingIntent);
    }

    private long getMusicAlarmLimitInner() {
        if (pendingIntent != null){
            return stopMusicTimeMillis - SystemClock.elapsedRealtime();
        }
        return 0;
    }

    public Music getCurrentMusicInner(){
        return currentMusic;
    }

    public boolean isPlayingInner(){
        return player.isPlaying();
    }

    public List<Music> getPlayingListInner(){
        return playingMusicList;
    }

    // 获取播放模式
    private int getPlayModeInner(){

        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(this);
        return sp.getInt("play_model", TYPE_ORDER);
    }
    // 设置播放模式
    private void setPlayModeInner(int mode){
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("play_model", mode);
        editor.commit();
    }

    // 设置重低音
    private void setStrengthInner(int progress){
        mBass.setStrength((short) progress);
    }
    private int  getStrengthInner(){
        return mBass.getRoundedStrength();
    }
    // 将要播放的音乐载入MediaPlayer，但是并不播放
    private void prepareToPlay(Music item) {
        try {
            player.stop();
            player.reset();
            String proxyUrl = proxy.getProxyUrl(item.musicUrl);
            //设置播放音乐的地址
            player.setDataSource(MusicService.this, Uri.parse(proxyUrl));

            //准备播放音乐
            player.prepare();
        } catch (IOException e) {
            Log.i("MusicService-------", "prepareToPlay.IOException(): " + item.musicName);
            e.printStackTrace();
        }
    }

    // 播放音乐，根据reload标志位判断是非需要重新加载音乐
    private void playMusicItem(Music item, boolean reload) {

        if (item == null) {
            return;
        }

        if (reload) {
            Log.i("MusicService-------", "player.start(): " + item.musicName);
            //需要重新加载音乐
            prepareToPlay(item);
        }
        player.start();
        for (OnStateChangeListenr l : listenrList) {
            l.onPlay(item);
        }
        isNeedReload = true;
        EventBus.getDefault().post(new MusicChangeEvent(item.id));
        //移除现有的更新消息，重新启动更新
        handler.removeMessages(66);
        handler.sendEmptyMessage(66);
    }

    // 初始化播放列表
    private void initPlayList() {
        playingMusicList = new ArrayList<>();
        List<PlayingMusic> list = new ArrayList<>();//LitePal.findAll(PlayingMusic.class);
        for (PlayingMusic music : list) {
            Music m = new Music(music.id, music.musicName,music.musician,music.musicDuration,music.region,music.musicUrl,music.cateId,music.cateName,music.isOnlineMusic,music.isFav);
            playingMusicList.add(m);
        }
        if (playingMusicList.size() > 0) {
            currentMusic = playingMusicList.get(0);
            isNeedReload = true;
        }
    }

    //当前歌曲播放完成的监听器
    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {

//            Utils.count ++; //累计听歌数量+1

            if (getPlayModeInner() == TYPE_SINGLE) {
                //单曲循环
                isNeedReload = true;
                Log.i("MusicService-------", "单曲循环");
                playInner();
            }
            else {
                Log.i("MusicService-------", "MediaPlayer.OnCompletionListener");
                playNextInner();
            }
        }
    };
    private MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer player, int what, int extra) {
            if (player.isPlaying()) {
                player.stop();
            }
            return false;
        }
    };

    private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener(){
        public void onPrepared(MediaPlayer mp) {
            player.start();
        }
    };




    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 66:
                    //通知监听者当前的播放进度
                    long played = player.getCurrentPosition();
                    long duration = player.getDuration();
                    for (OnStateChangeListenr l : listenrList) {
                        l.onPlayProgressChange(played, duration);
                    }
                    //间隔一秒发送一次更新播放进度的消息
                    sendEmptyMessageDelayed(66, 500);
                    break;
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        //当组件bindService()之后，将这个Binder返回给组件使用
        return binder;
    }

    //焦点控制
    private AudioManager.OnAudioFocusChangeListener audioFocusListener = new AudioManager.OnAudioFocusChangeListener(){

        public void onAudioFocusChange(int focusChange) {
            switch(focusChange){
                case AudioManager.AUDIOFOCUS_LOSS:
                    if(player.isPlaying()){
                        //会长时间失去，所以告知下面的判断，获得焦点后不要自动播放
                        autoPlayAfterFocus = false;
                        pauseInner();//因为会长时间失去，所以直接暂停
                    }
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    if(player.isPlaying()){
                        //短暂失去焦点，先暂停。同时将标志位置成重新获得焦点后就开始播放
                        autoPlayAfterFocus = true;
                        pauseInner();
                    }
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    if(player.isPlaying()){
                        //短暂失去焦点，先暂停。同时将标志位置成重新获得焦点后就开始播放
                        autoPlayAfterFocus = true;
                        pauseInner();
                    }
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    //重新获得焦点，且符合播放条件，开始播放
                    if(!player.isPlaying()&& autoPlayAfterFocus){
                        autoPlayAfterFocus = false;
                        Log.i("MusicService-------", "重新获得焦点，且符合播放条件，开始播放 ");
                        playInner();
                    }
                    break;
            }
        }
    };
    public static final String STOP_MUSIC_ACTION = "STOP_MUSIC_ACTION";

    BroadcastReceiver stopMusicReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (STOP_MUSIC_ACTION.equals(action)) {
                //音乐暂停
                Music item = getCurrentMusicInner();
                if(item != null && isPlayingInner()) {
                    pauseInner();
                }
            }
        }
    };

}
